package com.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.mall.constant.MessageConstant;
import com.mall.constant.StatusConstant;
import com.mall.context.BaseContext;
import com.mall.dto.BrandDTO;
import com.mall.dto.BrandPageQueryDTO;
import com.mall.exception.BaseException;
import com.mall.po.Brand;
import com.mall.mapper.BrandMapper;
import com.mall.po.Goods;
import com.mall.result.PageResult;
import com.mall.service.BrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 品牌表 服务实现类
 * </p>
 *
 * @author itlxc
 * @since 2024-04-18
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    /**
     * 品牌分页查询
     * @param brandPageQueryDTO
     * @return
     */
    @Override
    public PageResult brandPageQuery(BrandPageQueryDTO brandPageQueryDTO) {
        // 查询条件
        LambdaQueryWrapper<Brand> queryWrapper = new LambdaQueryWrapper<Brand>()
                .like(StringUtils.isNotBlank(brandPageQueryDTO.getName()),
                        Brand::getName, brandPageQueryDTO.getName())
                .eq(brandPageQueryDTO.getStatus() != null,
                        Brand::getStatus, brandPageQueryDTO.getStatus())
                .orderByDesc(Brand::getUpdateTime);
        Page<Brand> page = page(new Page<>(brandPageQueryDTO.getPage(), brandPageQueryDTO.getPageSize()), queryWrapper);
        return new PageResult(page.getTotal(), page.getRecords());
    }

    /**
     * 删除品牌
     * @param ids
     */
    @Override
    @Transactional
    public void deleteBrand(List<Long> ids) {
        // 启用中的品牌无法删除
        List<Brand> brandList = listByIds(ids);
        brandList.forEach(brand -> {
            if (Objects.equals(brand.getStatus(), StatusConstant.ENABLE)) {
                throw new BaseException(MessageConstant.BRAND_NOT_DEL);
            }
        });
        // 该品牌下有商品无法删除
        List<Goods> goodsList = Db.lambdaQuery(Goods.class)
                                    .in(Goods::getBrandId, ids)
                                    .list();
        if (CollUtil.isNotEmpty(goodsList)) {
            throw new BaseException(MessageConstant.BRAND_BE_RELATED_BY_GOOD);
        }
        removeBatchByIds(ids);
    }

    /**
     * 启用、禁用品牌
     * @param status
     * @param id
     */
    @Override
    @Transactional
    public void startOrStopBrand(Integer status, Long id) {
        Brand brand = Brand.builder()
                            .status(status)
                            .id(id)
                            .build();
        updateById(brand);
        // 如果品牌禁用，该品牌下的商品也要禁用
        if (Objects.equals(status, StatusConstant.DISABLE)) {
            Db.lambdaUpdate(Goods.class)
                    .set(Goods::getStatus, StatusConstant.DISABLE)
                    .set(Goods::getUpdateTime, LocalDateTime.now())
                    .set(Goods::getUpdateUser, BaseContext.getCurrentId())
                    .eq(Goods::getBrandId, id)
                    .update();
        }
    }
}
